package com.springsecurity.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.springsecurity.demo.mapper.SysUserMapper;
import com.springsecurity.demo.mapper.UsersMapper;
import com.springsecurity.demo.model.entity.LoginUser;
import com.springsecurity.demo.model.entity.SysUser;
import com.springsecurity.demo.model.entity.Users;
import com.springsecurity.demo.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UsersMapper userMapper;

    @Autowired
    private ISysMenuService iSysMenuService;

    @Autowired
    private SysUserMapper sysUserMapper;

//    @Autowired
//    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //查询用户信息
//        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Users::getUsername, username);
//        Users user = userMapper.selectOne(queryWrapper);
//        //如果没有查询到用户就抛出异常
//        if(Objects.isNull(user)){
//            throw new RuntimeException("用户名或者密码错误");
//        }

//        List<String> list = new ArrayList<>(Arrays.asList("test","admin"));
//        List<String> list = menuMapper.selectPermsByUserId(user.getId());
        //把数据封装成UserDetails返回
//        return new LoginUser(user,list);

        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUserName, username);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        //如果没有查询到用户就抛出异常
        if(Objects.isNull(sysUser)){
            throw new RuntimeException("用户名或者密码错误");
        }
        List<String> permissions = iSysMenuService.getMenuInfoByOneUserId(sysUser.getId());

//        List<String> permissions = Arrays.asList("testAuthorization");
//        List<String> permissions = Arrays.asList("testAuthorization");
//        return new LoginUser(user.getUsername(), user.getPassword(), permissions);
        return new LoginUser(sysUser.getUserName(), sysUser.getPassword(), permissions);
    }
}

